<template>
	<div class="home">
		<van-nav-bar title="设置个人信息" />

		<van-form @submit="onSubmit">
			<van-field v-model="form.name" name="姓名" label="姓名" placeholder="请输入姓名" :rules="nameRule" />
			<van-field v-model="form.identity" name="身份证号" label="身份证号" placeholder="请输入身份证号" :rules="identityRule" />
			<div style="margin: 16px;">
				<van-button plain block type="info" native-type="submit">保存</van-button>
			</div>
		</van-form>
	</div>
</template>

<script>
	import {
		Toast
	} from "vant";
	import userApi from '@/api/userApi'; // 用户数据接口

	export default {
		name: 'Login',
		data() {
			return {
				form: {
					name: '',
					identity: '',
				},
				nameRule: [{
					required: true,
					message: "请输入姓名",
					trigger: "onBlur"
				}],
				identityRule: [{
						required: true,
						message: "请输入身份证号",
						trigger: "onBlur"
					},
					{
						validator: value => {
							return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value);
						},
						message: "身份证号码格式不正确"
					}
				],
        userInfo:{}
			}
		},
		methods: {
			onSubmit() {
				// 从localStorage获取用户id
				var userInfo = JSON.parse(localStorage.getItem("userInfo"));
				this.form.id = userInfo.id
				userApi.edit(this.form).then(res => {
					if (res.data.code === 200) { // 保存成功
            userApi.queryUserInfo().then(res => {
              if (res.data.code === 200) {
                this.userInfo = JSON.stringify(res.data.data)
                // 将用户信息存储在localStorage
                localStorage.setItem("userInfo", this.userInfo)
              }
            })
						// 跳转到首页
						this.$router.push({
							path: `/antigenHome`
						})
					} else { // 保存失败
						// 弹出后台返回的错误信息
						Toast(res.data.message)
					}
				})
			},
			registerPhone() {
				this.$router.push('/register')
			},
		}
	}
</script>

<style>
</style>
